using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BallBase : MonoBehaviour
{
    [HideInInspector]
    public Rigidbody _rigidbody;

    public GameObject Shadow;
    public GameObject Model;

    private Vector3 StartShadowPos;
    public float StartShadowPosY;

    public AudioSource PocketAudioSource;

    [Header("视觉旋转参数")]
    public float ballRadius = 0.5f; // 球的半径
    private Vector3 prevPosition;   // 上一帧的位置

    // Start is called before the first frame update
    protected virtual void Awake()
    {
        _rigidbody = GetComponent<Rigidbody>();
        if (Shadow == null) {
            return;
        }
        StartShadowPos = Shadow.transform.position - transform.position;
        StartShadowPosY = Shadow.transform.position.y;
        
        // 初始化位置记录
        prevPosition = transform.position;
    }

    // Update is called once per frame
    void LateUpdate()
    {
            // if (Model != null)
            // {
            //     // 计算位置变化
            //     Vector3 movement = transform.position - prevPosition;
                
            //     if (movement.magnitude > 0.001f)
            //     {
            //         // 计算旋转角度
            //         // 移动距离 = 旋转角度 * 半径
            //         // 因此旋转角度 = 移动距离 / 半径
            //         float rotationAngle = (movement.magnitude / ballRadius) * Mathf.Rad2Deg;
                    
            //         // 计算旋转轴（与运动方向垂直且平行于地面）
            //         Vector3 rotationAxis = Vector3.Cross(Vector3.up, movement.normalized);
                    
            //         // 应用旋转
            //         Model.transform.Rotate(rotationAxis, rotationAngle, Space.World);
            //     }
                
            //     // 更新位置记录
            //     prevPosition = transform.position;
            // }

        if (Shadow != null)
        {
            RefreshShadow();
        }
    }
    public virtual void FixedUpdate()
    {
        float currentSpeed = _rigidbody.velocity.magnitude;
        if (currentSpeed < 0.2f && currentSpeed > 0.001f)
        {
            _rigidbody.velocity = Vector3.zero;
            _rigidbody.angularVelocity = Vector3.zero;
        }
    }

    void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.layer == 9)
        {
            _rigidbody.velocity = Vector3.zero;
            _rigidbody.angularVelocity = Vector3.zero;
            PocketAudioSource.Play();
        }
    }

    private void RefreshShadow()
    {
        Shadow.transform.position = new Vector3(transform.position.x + StartShadowPos.x,
            0.07085563f,
            transform.position.z + StartShadowPos.z);
        Shadow.transform.eulerAngles = new Vector3(0, 180, 0);
    }
}
